package com.atguigu.yuntai.web.controller.govern;

import com.atguigu.yuntai.common.util.Result;
import com.atguigu.yuntai.govern.entity.GovernanceDetail;
import com.atguigu.yuntai.govern.entity.GovernanceGlobal;
import com.atguigu.yuntai.govern.entity.GovernanceOption;
import com.atguigu.yuntai.govern.service.GovernanceDetailService;
import com.atguigu.yuntai.govern.service.GovernanceGlobalService;
import com.atguigu.yuntai.govern.service.GovernanceOptionService;
import com.atguigu.yuntai.govern.service.TableInfoService;
import com.atguigu.yuntai.web.controller.govern.bean.GovernanceProblemTab;
import com.atguigu.yuntai.web.controller.govern.bean.GovernanceSumScore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 数据治理 前端控制器
 */
@RestController
@RequestMapping("/govern/governance")
@Api(tags = "数据治理")
//@CrossOrigin //跨域
@Slf4j
public class GovernanceController {

    @Autowired
    GovernanceGlobalService governanceGlobalService;

    @Autowired
    GovernanceDetailService governanceDetailService;

    @Autowired
    GovernanceOptionService governanceOptionService;

    @Autowired
    TableInfoService tableInfoService;

    /**
     * 获取健康度总分
     *
     * @return
     */
    @ApiOperation(value = "获取健康度总分")
    @GetMapping("/globalScore")
    @CrossOrigin
    public Result getLastestGlobalScore() {

        //获取数据治理全局得分
        GovernanceGlobal governanceGlobal = governanceGlobalService.getOne(new QueryWrapper<GovernanceGlobal>().orderByDesc("id").last("limit 1"));
        GovernanceSumScore governanceSumScore = new GovernanceSumScore();
        //获取健康度分数并确定等级
        governanceSumScore.setSumScore(governanceGlobal.getScore());
        if (governanceGlobal.getScore().compareTo(BigDecimal.valueOf(90)) > 0) {
            governanceSumScore.setScoreLevel("优");
        } else if (governanceGlobal.getScore().compareTo(BigDecimal.valueOf(75)) > 0) {
            governanceSumScore.setScoreLevel("良");
        } else if (governanceGlobal.getScore().compareTo(BigDecimal.valueOf(60)) > 0) {
            governanceSumScore.setScoreLevel("中");
        } else {
            governanceSumScore.setScoreLevel("差");
        }

        //获取每种治理类型的分数
        List<BigDecimal> scoreList = new ArrayList<>();
        //计算得分
        scoreList.add(governanceGlobal.getScoreCalc());
        //存储得分
        scoreList.add(governanceGlobal.getScoreStorage());
        //规范得分
        scoreList.add(governanceGlobal.getScoreSpec());
        //安全得分
        scoreList.add(governanceGlobal.getScoreSecurity());
        //质量得分
        scoreList.add(governanceGlobal.getScoreQuality());

        governanceSumScore.setSumScore(governanceGlobal.getScore());
        governanceSumScore.setScoreList(scoreList);
        return Result.ok(governanceSumScore);
    }

    /**
     * 获取总成本(数据表、存储量)
     *
     * @return
     */
    @ApiOperation(value = "获取总成本(数据表、存储量)")
    @GetMapping("/globalSize")
    @CrossOrigin
    public Result getLastestGlobalSize() {
        //获取存储量
        return Result.ok(tableInfoService.getGlobalTableSize());
    }

    /**
     * 根据类型查询治理信息(选项)
     *
     * @param optionType
     * @return
     */
    @ApiOperation(value = "根据类型查询治理信息(选项)")
    @GetMapping("/governanceOptions/{optionType}")
    @CrossOrigin
    public Result getGovernanceOptions(
            @ApiParam(name = "optionType", value = "治理新类型", required = true)
            @PathVariable String optionType) {

        //治理类型：spec:规范;quality:质量;storage:存储;calc:计算;security:安全
        String[] optionTypesSys = {"spec", "quality", "storage", "calc", "security"};
        if (!Arrays.asList(optionTypesSys).contains(optionType)) {
            return Result.fail(HttpStatus.BAD_REQUEST);
        }
        //根据治理类型查询治理明细
        Map<String, List<GovernanceDetail>> governanceDetailMap = governanceDetailService.getGovernanceDetailMapToFixByType(optionType.toUpperCase());
        //获取治理项的详细信息
        Map<String, List<GovernanceOption>> optionListMap = governanceOptionService.getGovernanceOptionGroupByType();
        List<GovernanceOption> governanceOptionList = optionListMap.get(optionType.toUpperCase());
        List<GovernanceProblemTab> governanceProblemTabList = new ArrayList<>();
        for (GovernanceOption governanceOption : governanceOptionList) {
            GovernanceProblemTab governanceProblemTab = new GovernanceProblemTab();
            //治理项编码
            governanceProblemTab.setOptionCode(governanceOption.getOptionCode());
            //治理项描述
            governanceProblemTab.setOptionDesc(governanceOption.getOptionDesc());
            //治理项集合
            List<GovernanceDetail> governanceDetailList = governanceDetailMap.getOrDefault(governanceOption.getOptionCode(), new ArrayList<>());
            governanceProblemTab.setGovernanceDetailSize(governanceDetailList.size());
            governanceProblemTabList.add(governanceProblemTab);
        }
        return Result.ok(governanceProblemTabList);
    }

    /**
     * 根据治理项编码查询治理详细信息（分页）
     *
     * @param page
     * @param limit
     * @param optionCode
     * @return
     */
    @ApiOperation(value = "根据治理项编码查询治理详细信息")
    @GetMapping("/governanceDetail/{optionCode}/{page}/{limit}")
    @CrossOrigin
    public Result getGovernanceDetailByType(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,

                                            @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit,

                                            @ApiParam(name = "optionCode", value = "治理项编码", required = true) @PathVariable String optionCode) {
        Page<GovernanceDetail> pageParam = new Page<>(page, limit);
        IPage<GovernanceDetail> governanceDetailList = governanceDetailService.page(pageParam, new QueryWrapper<GovernanceDetail>().eq("option_code", optionCode).eq("governance_result", 0).inSql("busi_date", "select max(busi_date) from governance_detail"));
        return Result.ok(governanceDetailList);
    }


}
